# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.


from odoo import api, http, SUPERUSER_ID, _
from odoo.http import request

from odoo import registry as registry_get

import base64

from odoo.addons.web_patch.controllers.main import Access


class PdfUpload(http.Controller):

    @http.route('/web2/upload', type='http', auth='public')
    def upload(self, *args, **kw):
        print('ssss,', args, kw)

        if request.httprequest.method == 'POST':
            ufile = kw.get('file')
            dbname = kw.get('dbname')
            # print(ufile, type(ufile))
            if not dbname:
                return {'error': 'no dbname'}

            if not ufile:
                return {'error': 'no file'}

            try:
                # create an empty registry
                registry = registry_get(dbname)
                with registry.cursor() as cr:
                    env = api.Environment(cr, SUPERUSER_ID, {})

                    Model = env['ir.attachment']
                    filename = ufile.filename

                    attachment = Model.search(
                        [('name', '=', filename)], limit=1)

                    if not attachment:
                        attachment = Model.create({
                            'name': filename,
                            'datas': base64.encodebytes(ufile.read()),
                            # 'res_model': model,
                            # 'res_id': int(id)
                        })

                    print(attachment)

                    #
                    # content_type = ufile.content_type
                    # s = ufile.read()

                    # print(s)
                    # print(filename)
                    # print(content_type)
                    response = request.render('vwat_fapiao.upload_ok')
                    return response

            except Exception:
                return {'error': 'no file'}

        else:

            response = request.render('vwat_fapiao.upload')
            return response


class AccessVW(Access):
    @http.route('/vwat/access/token', type='json', auth="none",  cors='*', csrf=False)
    def vw_access_token(self, taxno, appkey, appsecret):
        return self.access_token(taxno, appkey, appsecret)

    @http.route('/vwat/test_api', type='json', auth="none", cors='*', csrf=False)
    def vw_test_api(self, token, p1, p2):
        print('vw_test_api', token)
        db, uid = self.check_token(token)
        registry = registry_get(db)
        with registry.cursor() as cr:
            env = api.Environment(cr, uid, {})
            # partner = env['res.partner']
            # return partner.search_read([], fields=['name'])

            res = 'you call success by (' + str(p1) + ',' + str(p2) + ')'
            return res

    @http.route('/vwat/test', type='json', auth="none", cors='*', csrf=False)
    def vw_test(self, token, **kw):
        db, uid = self.check_token(token)
        registry = registry_get(db)
        with registry.cursor() as cr:
            env = api.Environment(cr, uid, {})
            print('vw_test', kw)
            partner = env['res.partner']
            return partner.search_read([], fields=['name', 'image_1920'])

    @http.route('/vwat/invoice/upload', type='json', auth="none", cors='*', csrf=False)
    def vw_invoice_upload(self, token, **kw):
        db, uid = self.check_token(token)
        registry = registry_get(db)
        with registry.cursor() as cr:
            env = api.Environment(cr, uid, {})
            return {
                'invoice_type': 'vat_genaral_e',  # 发票类型
                'code': '011002100111',  # 发票代码
                'number': '15151122',  # 发票号码
                'usage': False  # 使用情况
            }

    @http.route('/vwat/invoice/list', type='json', auth="none", cors='*', csrf=False)
    def vw_invoice_list(self, token, **kw):
        db, uid = self.check_token(token)
        registry = registry_get(db)
        with registry.cursor() as cr:
            env = api.Environment(cr, uid, {})

            partner = env['res.partner']
            res = partner.search_read([('name', '=', 'Apon')],
                                      fields=['name', 'image_1920'])

            img = res[0]['image_1920']

            return [
                {
                    'invoice_type': 'vat_genaral_e',  # 发票类型
                    'code': '011002100111',  # 发票代码
                    'number': '15151001',  # 发票号码
                    'amount_total': 1130.0,  # 含税总金额
                    'amount_untax': 1000.0,  # 不含税总金额
                    'amount_tax': 130.0,  # 税额
                    'data': '2022-08-28',  # 开票日期
                    'remark': '备注',  # 备注

                    # 信息核对是否一致(0表示一致,1表示供应商名称不一致,供应商账号银行一直；2表示供应商账号或开户银行不一致；3表示供应商名称不一致，账号或开户银行不一致)
                    'saler_check': 0,
                    'data_upload': '2022-08-29',  # 收票日期
                    'usage': 0,  # 使用情况(0表示未使用，1表示已使用)
                    'apon_number': '1456789xxxxxx',  # 申请单号
                    'file_url': 'http://ample.com/xxx',  # URL-发票源文件存储地址 URL地址
                    'image': img,  # 图片
                    'lines': [
                        {
                            'row_no': 1,
                            'product_name': '苹果笔记本',  # 商品名称
                            'product_spec': '4CPU,8G,256G',  # 规格
                            'product_uom': '台',  # 单位
                            'quantity': 10,  # 数量
                            'price': 1000,  # 不含税单价
                            'amount_untax': 10000.0,  # 不含税金额
                            'amount_tax': 1300.0,  # 税额
                        }
                    ]

                },

                {
                    'invoice_type': 'vat_genaral_e',  # 发票类型
                    'code': '011002100111',  # 发票代码
                    'number': '15151222',  # 发票号码
                    'amount_total': 1130.0,  # 含税总金额
                    'amount_untax': 1000.0,  # 不含税总金额
                    'amount_tax': 130.0,  # 税额
                    'data': '2022-08-28',  # 开票日期
                    'remark': '备注',  # 备注

                    # 信息核对是否一致(0表示一致,1表示供应商名称不一致,供应商账号银行一直；2表示供应商账号或开户银行不一致；3表示供应商名称不一致，账号或开户银行不一致)
                    'saler_check': 0,
                    'data_upload': '2022-08-29',  # 收票日期
                    'usage': 0,  # 使用情况(0表示未使用，1表示已使用)
                    'apon_number': '1456789xxxxxx',  # 申请单号
                    'file_url': 'http://ample.com/xxx',  # URL-发票源文件存储地址 URL地址
                    'image': img,  # 图片
                    'lines': [
                        {
                            'row_no': 1,

                            'product_name': '苹果笔记本',  # 商品名称
                            'product_spec': '4CPU,8G,256G',  # 规格
                            'product_uom': '台',  # 单位
                            'quantity': 10,  # 数量
                            'price': 1000,  # 不含税单价
                            'amount_untax': 10000.0,  # 不含税金额
                            'amount_tax': 1300.0,  # 税额
                        },
                        {
                            'row_no': 2,

                            'product_name': '苹果笔记本',  # 商品名称
                            'product_spec': '4CPU,8G,256G',  # 规格
                            'product_uom': '台',  # 单位
                            'quantity': 10,  # 数量
                            'price': 1000,  # 不含税单价
                            'amount_untax': 10000.0,  # 不含税金额
                            'amount_tax': 1300.0,  # 税额
                        },
                        {
                            'product_name': '苹果笔记本',  # 商品名称
                            'product_spec': '4CPU,8G,256G',  # 规格
                            'product_uom': '台',  # 单位
                            'quantity': 10,  # 数量
                            'price': 1000,  # 不含税单价
                            'amount_untax': 10000.0,  # 不含税金额
                            'amount_tax': 1300.0,  # 税额
                        },
                    ]

                },

            ]

    @http.route('/vwat/invoice/delete', type='json', auth="none", cors='*', csrf=False)
    def vw_invoice_delete(self, token, code, number, **kw):
        db, uid = self.check_token(token)
        registry = registry_get(db)
        with registry.cursor() as cr:
            env = api.Environment(cr, uid, {})
            return {
                'code': '011002100111',  # 发票代码
                'number': '15151122',  # 发票号码
                'action_flag': True  # True or False 操作结果是否成功
            }

    @http.route('/vwat/invoice/update', type='json', auth="none", cors='*', csrf=False)
    def vw_invoice_update(self, token, code, number, apon_number, apon_status, **kw):
        db, uid = self.check_token(token)
        registry = registry_get(db)
        with registry.cursor() as cr:
            env = api.Environment(cr, uid, {})
            return {
                'code': '011002100111',  # 发票代码
                'number': '15151122',  # 发票号码
                'action_flag': True  # True or False 操作结果是否成功
            }
